package com.regex.web.controller.community;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.regex.web.base.BaseController;
import com.regex.web.cache.DictCacheService;
import com.regex.web.entity.community.CommunityTypeDTO;
import com.regex.web.entity.community.NoticeCommentDTO;
import com.regex.web.entity.community.NoticeDTO;
import com.regex.web.entity.sys.UserDTO;
import com.regex.web.service.community.ICommunityTypeService;
import com.regex.web.service.community.INoticeCommentService;
import com.regex.web.service.community.INoticeService;
import com.regex.web.utils.AjaxUtil;
import com.regex.web.utils.Contant;
import com.regex.web.utils.HTMLSpiritUtil;
import com.regex.web.utils.QueryParam;
import com.regex.web.utils.QueryResult;

/**
 * 
 * 〈一句话功能简述〉<br> 
 * 小区通知公告
 *
 * @author admin
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@EnableAutoConfiguration
@RequestMapping("sys/notice")
public class SysNoticeController extends BaseController {
    
    private final static Logger logger = LoggerFactory.getLogger(SysNoticeController.class);

    @Autowired
    private DictCacheService memCacheService;
    
//    @Autowired
//    private IVillageService villageService;

    @Autowired
    private INoticeService noticeService;
    
    @Autowired
    private ICommunityTypeService communityTypeService;
    
    @Autowired
    private INoticeCommentService noticeCommentService;
    
//    @Value("${SEND_ADD_TASK_MESSAGE_URL}")
//    private String SEND_ADD_TASK_MESSAGE_URL;
    
    @RequiresPermissions("notice:show")
    @RequestMapping("show")
    public String show(QueryParam param, Model model) {
//        List<Long> villageIdList = memCacheService.getUserVillageIdListRole();
        
        if(param.getPageSize() <= 0) {
            param.setPageSize(Contant.NONMAL_PAGE_SIZE);
        }
        if(param.getPageNumber() < 1) {
            param.setPageNumber(1);
        }
        
        Page<NoticeDTO> page = new Page<NoticeDTO>();
        page.setSize(param.getPageSize());
        page.setCurrent(param.getPageNumber());
        logger.error("page == "+ JSON.toJSONString(page));
        QueryWrapper<NoticeDTO> queryWrapper = new QueryWrapper<NoticeDTO>();
//        if(StringUtils.isNotEmpty(villageId)) {
//            queryWrapper.eq("village_id", villageId);
//        } else {
//            queryWrapper.in("village_id", villageIdList);
//        }
        queryWrapper.eq("type", "1");
        queryWrapper.orderByDesc("is_top DESC,state ASC, create_time");
        logger.error("queryWrapper == "+ JSON.toJSONString(queryWrapper));
        QueryResult<NoticeDTO> result = noticeService.page(page, queryWrapper);
        for(NoticeDTO noticDTO :result.getDatas()) {
            String content = HTMLSpiritUtil.delHTMLTag(noticDTO.getContent());
            noticDTO.setContent(content);
//            VillageDTO villageDTO = villageService.getById(noticDTO.getVillageId());
//            if(villageDTO != null) {
//                noticDTO.setVillageName(villageDTO.getName());
//            }
            CommunityTypeDTO communityTypeDTO = communityTypeService.getById(Long.parseLong(noticDTO.getType()));
            if(communityTypeDTO!= null ) {
                noticDTO.setTypeName(communityTypeDTO.getName());
            }
            
            QueryWrapper<NoticeCommentDTO> NoticeCommentQueryWrapper = new QueryWrapper<NoticeCommentDTO>();
            NoticeCommentQueryWrapper.eq("notice_id", noticDTO.getId());
            NoticeCommentQueryWrapper.eq("audit", "0");
            int commontAuditCount  = (int) noticeCommentService.count(NoticeCommentQueryWrapper);
            noticDTO.setCommontAuditCount(commontAuditCount);
        }
        
        model.addAttribute("result", result);
        
        Map<String, Object> dictMap = memCacheService.getDictCache();
        model.addAttribute("dictMap", dictMap);
        return "sys/notice/show";
    }
    
    
    /**
     * 
     * 功能描述: <br>
     * 详情
     *
     * @param id
     * @param model
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequiresPermissions("notice:show")
    @RequestMapping("detial")
    public String detial(Long id, Model model) {
        try {
            NoticeDTO NoticeDTO = noticeService.getById(id);
            model.addAttribute("NoticeDTO", NoticeDTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "sys/notice/detial";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 删除
     *
     * @param id
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequiresPermissions("notice:del")
    @RequestMapping("del")
    public void del(Long id, HttpServletResponse response) {
        int n = 0;
        boolean flag = noticeService.removeById(id);
        if(flag) {
            n = 1;
        }
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    @RequestMapping("isTop")
    public void isTop(Long id, HttpServletResponse response) {
        int n = 0;
        NoticeDTO NoticeDTO = noticeService.getById(id);
        NoticeDTO.setIsTop("1");
        boolean flag = noticeService.updateById(NoticeDTO);
        if(flag) {
            n = 1;
        }
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }
    
    @RequestMapping("cacleIsTop")
    public void cacleIsTop(Long id, HttpServletResponse response) {
        int n = 0;
        NoticeDTO NoticeDTO = noticeService.getById(id);
        NoticeDTO.setIsTop("0");
        boolean flag = noticeService.updateById(NoticeDTO);
        if(flag) {
            n = 1;
        }
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }    
    
    @RequestMapping("getCommunityTypeList")
    public void getCommunityTypeList(HttpServletResponse response, String villageId) {
        
        QueryWrapper<CommunityTypeDTO> communityTypeQueryWrapper = new QueryWrapper<CommunityTypeDTO>();
        communityTypeQueryWrapper.eq("type", "0");
        communityTypeQueryWrapper.eq("village_id", villageId);
        List<CommunityTypeDTO> communityTypeList = communityTypeService.list(communityTypeQueryWrapper);
        AjaxUtil.ajaxJsonSucMessage(response, communityTypeList);
    }
    
    /**
     * 
     * 功能描述: <br>
     * 修改/ 新增
     *
     * @param id
     * @param model
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequiresPermissions("notice:edit")
    @RequestMapping("input")
    public String input(Long id, Model model, String villageId) {
        if(id!= null && id > 0) {
            NoticeDTO NoticeDTO = noticeService.getById(id);
            villageId = NoticeDTO.getVillageId() + "";
            model.addAttribute("NoticeDTO", NoticeDTO);
        }
        model.addAttribute("villageId", villageId);
        
        QueryWrapper<CommunityTypeDTO> communityTypeQueryWrapper = new QueryWrapper<CommunityTypeDTO>();
        communityTypeQueryWrapper.eq("type", "0");
        List<CommunityTypeDTO> communityTypeList = communityTypeService.list(communityTypeQueryWrapper);
        model.addAttribute("communityTypeList", communityTypeList);
        return "sys/notice/input";
    }
    
    /**
     * 
     * 功能描述: <br>
     * 保存
     *
     * @param NoticeDTO
     * @param response
     * @param request
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequiresPermissions("notice:edit")
    @RequestMapping("save")
    public void save(NoticeDTO NoticeDTO, HttpServletResponse response,
            HttpServletRequest request) {
        int n = 0;
        UserDTO userDTO = getUser();
        try {
        if(StringUtils.isNotEmpty(NoticeDTO.getContent())) {
            NoticeDTO.setUpdateTime(new Date());
            if(NoticeDTO.getId() > 0) {
                boolean flag = noticeService.updateById(NoticeDTO);
                if(flag) {
                    n = 1;
                }
            } else {
                NoticeDTO.setCreateUser(userDTO.getId());
                NoticeDTO.setIsDel("0");
                NoticeDTO.setCreateTime(new Date());
                NoticeDTO.setIsTop("0");
                NoticeDTO.setAudit(0l);
                boolean flag = noticeService.save(NoticeDTO);
                if(flag) {
                    n = 1;
                }
            }
            
//            if("1".equals(NoticeDTO.getIsSend())) {
//                TaskJobInfoDTO taskJobInfo = new TaskJobInfoDTO();
//                taskJobInfo.setClasses("com.zhsq.app.job.SendNoticeMessageJob");
//                taskJobInfo.setDiscription("公告消息发送任务");
//                taskJobInfo.setIsDel(Contant.is_del_undelete);
//                taskJobInfo.setName("公告消息发送任务");
//                taskJobInfo.setCreateTime(new Date());
//                taskJobInfo.setUpdateTime(new Date());
//                taskJobInfo.setState("1");
//                taskJobInfo.setParameter(NoticeDTO.getId() + "");
//                
//                String taskJson = JSON.toJSONString(taskJobInfo);
//                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("taskJson", taskJson);
//                String resultStr = HttpSendSMS.sendSms(SEND_ADD_TASK_MESSAGE_URL, map);
//                ResultVO<?> result = JSON.parseObject(resultStr, ResultVO.class);
//                if(result.getCode() == 1) {
//                    logger.error("SEND NOTICE MESSAGE SUCCESS");
//                } else {
//                    logger.error("SEND NOTICE MESSAGE ERROR");
//                }
//            }
        } else {
            n = 2;
        }
        } catch(Exception e) {
            e.printStackTrace();
            n = 3;
        }
        AjaxUtil.ajaxJsonSucMessage(response, n);
    }



}
